package com.hbter630.change.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbter630.change.entity.Category;
import com.hbter630.change.service.CategoryService;
import com.hbter630.change.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Title: AdminCategoryController
 * @Author 笑霸fianl
 * @Package com.hbter630.change.controller.admin
 * @Date 2023/5/28 15:23
 * @描述: 后台商品分类管理
 */

@RestController
@RequestMapping("/Admin/Category")
@Api(tags = "后台分类管理")
@Slf4j
public class AdminCategoryController {

    @Autowired
    private CategoryService categoryService;


    @ApiOperation(notes = "查早所有商品分类",value = " 查早所有商品分类",
            httpMethod = "GET", response = Result.class)
    @GetMapping("findList")
    public Result findList(){
        List<Category> list = categoryService.list();
        return Result.ok().addData(list);
    }


    @ApiOperation(notes = "根据id删除商品分类",value = " 根据id删除商品分类",
            httpMethod = "DELETE", response = Result.class)
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable("id") Long id){

        boolean b = categoryService.delete(id);
        return b?Result.ok():Result.failed("此分类下有商品不能删除");
    }

    @ApiOperation(notes = "找出名字",value = " 找出名字",
            httpMethod = "POST", response = Result.class)
    @PostMapping("findName")
    public Result findName(@RequestBody Category category){
        String name = category.getName();
        if(StrUtil.isEmpty(name)|| name.isEmpty()){
            return Result.failed().addMessage("请输入分类名");
        }
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.eq("name",name);
        Category one = categoryService.getOne(categoryQueryWrapper);
        if (BeanUtil.isEmpty(one)) {
            return Result.ok();
        }
        return Result.failed().addMessage("名字重复");
    }




    @ApiOperation(notes = "添加商品分类",value = " 添加商品分类",
            httpMethod = "POST", response = Result.class)
    @PostMapping("addCategory")
    public Result addCategory(@RequestBody Category category){
        String name = category.getName();
        if(StrUtil.isEmpty(name)|| name.isEmpty()){
            return Result.failed().addMessage("请输入分类名");
        }
        categoryService.save(category);
        return Result.ok();
    }

}
